import BaseComponent from "../../../redare/components/BaseComponent";
import React from "react";
import {Modal, Upload} from "antd";
import {PlusOutlined} from '@ant-design/icons';
import {RESOURCE_SERVICE} from "../../../common/ConstField";

function getBase64(file) {
    return new Promise((resolve, reject) => {
        const reader = new FileReader();
        reader.readAsDataURL(file);
        reader.onload = () => resolve(reader.result);
        reader.onerror = error => reject(error);
    });
}

export default class ImageUpload extends BaseComponent {

    static defaultProps = {
        maxUploadLength: 9,
        uploadTitle: '上传图片'
    }

    state = {
        previewVisible: false,
        previewImage: '',
        previewTitle: '',
        fileList: []
    };

    handleCancel = () => this.setState({previewVisible: false});

    handlePreview = async file => {
        if (!file.url && !file.preview) {
            file.preview = await getBase64(file.originFileObj);
        }

        this.setState({
            previewImage: file.url || file.preview,
            previewVisible: true,
            previewTitle: file.name || file.url.substring(file.url.lastIndexOf('/') + 1),
        });
    };

    handleChange = ({fileList}) => this.setState({fileList});


    initImage(images) {
        if (!images) {
            return;
        }
        if (images.constructor !== Array){
            images = images.split(',');
        }
        let imageUploadData = [];
        images.map((item,index) => {
            imageUploadData.push({
                url:item,
                uid:"image_upload_temp_" + index,
                status:'done'
            })
        });
        this.setState({fileList: imageUploadData});
    }

    getImageList() {
        let {fileList} = this.state;
        let imageList = [];
        fileList.forEach((item => {
            if (item.status === "done") {
                imageList.push(item.response.data)
            }
        }))
        return imageList;
    }

    getImages() {
        let {fileList} = this.state;
        let imageStr = '';
        let index = 0;
        fileList.forEach((item => {
            if (item.status === "done") {
                if (index !== 0) {
                    imageStr += ','
                }
                if (item.url){
                    imageStr += item.url
                }else{
                    imageStr += item.response.data.url
                }
                index += 1;
            }
        }))
        return imageStr;
    }

    render() {
        const {previewVisible, previewImage, fileList, previewTitle} = this.state;
        const uploadButton = (
            <div>
                <PlusOutlined/>
                <div style={{marginTop: 8}}>{this.props.uploadTitle}</div>
            </div>
        );
        return (
            <>
                <Upload
                    action={RESOURCE_SERVICE.FILE}
                    listType="picture-card"
                    fileList={fileList}
                    onPreview={this.handlePreview}
                    onChange={this.handleChange}
                >
                    {fileList.length >= this.props.maxUploadLength ? null : uploadButton}
                </Upload>
                <Modal
                    visible={previewVisible}
                    title={previewTitle}
                    footer={null}
                    onCancel={this.handleCancel}
                >
                    <img alt="example" style={{width: '100%'}} src={previewImage}/>
                </Modal>
            </>
        );
    }
}